package com.sc.nft.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.admin.request.*;
import com.sc.nft.admin.vo.LoginVO;
import com.sc.nft.admin.vo.SysMemberVO;
import com.sc.nft.annotation.SysMemberLogin;
import com.sc.nft.dao.DigitalCollectionProductInfoSubscribeDao;
import com.sc.nft.dao.DigitalCollectionProductInfoSubscribeWinBallotDao;
import com.sc.nft.dao.OrderDao;
import com.sc.nft.entity.Role;
import com.sc.nft.entity.SysMember;
import com.sc.nft.entity.vo.DigitalCollectionProductInfoDrawVo;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.helper.MessageQueueHelper;
import com.sc.nft.pool.SysMemberPool;
import com.sc.nft.service.DigitalCollectionProductInfoSubscribeCodeService;
import com.sc.nft.service.RoleService;
import com.sc.nft.service.SysMemberService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import com.sc.nft.util.RedisUtil;
import com.sc.nft.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息表服务控制器
 *
 * @author zhangxiangyu
 * @since 2021-10-04 22:54:13
 * @description
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/sysMember")
@Api(tags="后台管理用户模块")
public class SysMemberController {
    private final SysMemberService sysMemberService;
    private final RoleService roleService;
    private final OrderDao orderDao;
    private final RedisUtil redisUtil;
    private final MessageQueueHelper messageQueueHelper;

    @PostMapping(value="/login", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户登录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<LoginVO> login(@Valid @RequestBody LoginRequest loginRequest, HttpServletRequest request ) throws GlobalException, IOException {
        //登录日志

        SysMember sysMember = sysMemberService.login(loginRequest.getAccount(),loginRequest.getPassword());
        LoginVO loginVO = new LoginVO();
        BeanUtils.copyProperties(sysMember,loginVO);
        loginVO.setSex(sysMember.getUserSex());
        //获取角色信息
        Role role = roleService.queryById(sysMember.getRoleId());
        loginVO.setRoleName(role.getRoleName());
        String token = sysMemberLogin(sysMember.getId());
        loginVO.setToken(token);
        return Result.success(loginVO);
    }

    @PostMapping(value="/add", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "创建用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin(adminAuthority=true)
    public Result  add(@Valid  @RequestBody AddSysMemberRequest request)  {
        if(sysMemberService.checkUserAccountExists(request.getUserAccount())){
            return Result.fail(ErrorCode.ACCOUNT_EXISTS);
        }
        if(roleService.queryById(request.getRoleId())==null){
            return Result.fail(ErrorCode.ROLE_NO_EXISTS);
        }
        SysMember sysMember = new SysMember();
        BeanUtil.copyProperties(request,sysMember);
        sysMember.setUserPassword(SecureUtil.md5(request.getPwd()));
        sysMember.insert();
        return Result.success();
    }

    @PostMapping(value="/update", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "更新用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin(adminAuthority=true)
    public Result  update(@RequestBody UpdateSysMemberRequest request) {
        SysMember sysMember = new SysMember();
        BeanUtil.copyProperties(request,sysMember);
        sysMember.updateById();
        return Result.success();
    }
    @PostMapping(value="/updatePassword", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改密码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public Result updatePassword(@Valid @RequestBody UpdatePasswordRequest userRequest)   {
        SysMember sysMember= SysMemberPool.getMember();
        if(!StrUtil.equals(SecureUtil.md5(userRequest.getOldPassword()),sysMember.getUserPassword())){
            return Result.fail(ErrorCode.PASSWORD_ERROR);
        }
        sysMember.setUserPassword(SecureUtil.md5(userRequest.getPassword()));
        sysMember.updateById();
        return Result.success();
    }


    @PostMapping(value="/delSysMember", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result  delSysMember(@Valid @RequestBody IdRequest request)   {
        SysMember sysMember= sysMemberService.getById(request.getId());
        if(ObjectUtil.isNull(sysMember)){
            return Result.fail(ErrorCode.PARAM_ERROR);
        }else if(sysMember.getRoleId() == 1) {
            return Result.fail(ErrorCode.ADMINISTRATOR_CANNOT_DELETE);
        }
        sysMember.deleteById(sysMember.getId());
        return Result.success();
    }




    @PostMapping(value="/query", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public PageResult<SysMemberVO> query(@Valid @RequestBody QuerySysMemberRequest request) {
        Page<SysMember> page = sysMemberService.query(request.getUserAccount(),request.getRoleId(),request.getUserName(),request.getUserSex(),request.getStartBirthday(),request.getEndBirthday(),request.getPhone(),request.getPageNo(),request.getPageSize());
        return PageResult.success(page,SysMemberVO.class);
    }

    private String sysMemberLogin(Long id) {
        Assert.notNull(id);
        String token = TokenUtil.createAdminToken(id);
        redisUtil.del(RedisKeyEnum.ADMIN_MEMBER_INFO.getKey() + redisUtil.get(RedisKeyEnum.ADMIN_MEMBER_RELATION.getKey() + id));
        //存入redis
        redisUtil.set(TokenUtil.getRedisTokenAdminKey(token), id.toString(), 60 * 24 * 30);
        redisUtil.set(RedisKeyEnum.ADMIN_MEMBER_RELATION.getKey() + id, token, 60 * 24 * 30);
        return token;
    }




}